package servlet;

import Dao.JdbcTools;
import model.Student;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/islogin")
public class UserRequest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = req.getParameter("user");
        String pw = req.getParameter("pw");
        String code = req.getParameter("yz");
        System.out.println("user = " + user);
        System.out.println("pw = " + pw);
        System.out.println("code = " + code);
        //1判断用户输入的验证码和机器验证码是否相同
        HttpSession session = req.getSession();
        String yz = (String) session.getAttribute("yz");
        if (!yz.equals(code))
        {
            System.out.println("验证码错误！");
            return;
        }

        //访问Dao，查询记录
        String sql="select * from userpw where user=? and pw=?";
        try {
            User is = JdbcTools.queryBean(sql, User.class,user, pw);
            if(is==null)
            {
                //错误提示servlet
                req.getRequestDispatcher("usererror").forward(req,resp);
            }else{
                //只要成功登录则立即产产生各个页面共享的session值
                //因此每一个后端管理员是否拥有session共享值进行判断那个是否合法
                session.setAttribute("user","pw");
                //获取数据库中展示数据
                List<Student> stulist = JdbcTools.queryBeanList("select * from student", Student.class);
                //数据展示 servlet
//                req.setAttribute("stulist",stulist);
//                req.getRequestDispatcher("showlist").forward(req,resp);

//                req.setAttribute("stulist",stulist);
//                req.getRequestDispatcher("showlist2.jsp").forward(req,resp);

                req.setAttribute("stulist",stulist);
                req.getRequestDispatcher("showlist3.jsp").forward(req,resp);

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
